﻿using System;
using System.Threading;
using System.Threading.Tasks;
using static System.Threading.Thread;
using static System.Console;

namespace Project_4
{
    /// <summary>
    /// 4.2 使用任务的三种方式,Task任务默认是线程池,加了 TaskCreationOptions.LongRunning，任务长时间运行 后，就不是线程池了
    /// </summary>
    public class Unit_4_02
    {
        /*
         * 使用任务的三种方式：
           1.var t1 = new Task(()=>{});t1.start();
           2.Task.Run(()=>{});
           3.Task.Factory.  (()=>{});
           Task 任务默认是线程池，
           加了TaskCreationOptions.LongRunning，任务长时间运行 后，就不是线程池了
         */
        public static void Go()
        {
            var t1 = new Task(() => TaskMethod("Task 1"), TaskCreationOptions.LongRunning);
            var t2 = new Task(() => TaskMethod("Task 2"));
            t2.Start();
            t1.Start();
            Task.Run(() => TaskMethod("Task 3"));
            Task.Factory.StartNew(() => TaskMethod("Task 4"));
            Task.Factory.StartNew(() => TaskMethod("Task 5"), TaskCreationOptions.LongRunning);
            Sleep(TimeSpan.FromSeconds(1));
        }

        static void TaskMethod(string name)
        {
            WriteLine($"Task {name} is running on a thread id "+
                      $"{CurrentThread.ManagedThreadId}. 是否是线程池的线程 " +
                      $"{CurrentThread.IsThreadPoolThread}. ");
        }
    }
}
